package com.caiyigo.baihua.controller;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.caiyigo.baihua.Const.Const;
import com.caiyigo.baihua.dto.DataGrid;
import com.caiyigo.baihua.dto.Pager;
import com.caiyigo.baihua.dto.Result;
import com.caiyigo.baihua.dto.UserDto;
import com.caiyigo.baihua.model.SystemRole;
import com.caiyigo.baihua.model.SystemUser;
import com.caiyigo.baihua.service.RoleService;
import com.caiyigo.baihua.service.UserService;
import com.caiyigo.baihua.shiro.ShiroExt;
import com.caiyigo.baihua.utils.ListUtil;
import com.caiyigo.baihua.utils.Sec;
import com.github.miemiedev.mybatis.paginator.domain.Order;
import com.github.miemiedev.mybatis.paginator.domain.PageBounds;
import com.github.miemiedev.mybatis.paginator.domain.PageList;

/**
 * @author caihaihui
 * 
 */
@Controller
@RequestMapping(value = "/system/user")
public class UserController {
	@Autowired
	UserService userService;
	@Autowired
	RoleService roleService;

	@RequestMapping(value = "/list", method = RequestMethod.POST)
	public @ResponseBody DataGrid<UserDto> list(UserDto user, Pager page) {
		// 表单查询条件组装
		if (StringUtils.isNotEmpty(user.getRoleid())) {
			String[] flag = user.getRoleid().split(",");
			user.setRoleids(Arrays.asList(flag));
		}

		List<Order> orders = new ArrayList<Order>();
		orders.add(Order.create(page.getSort(), page.getOrder()));
		PageList<UserDto> pageList = (PageList<UserDto>) userService
				.getUserList(user,
						new PageBounds(page.getPage(), page.getRows(), orders,
								true));
		SystemUser now = ShiroExt.getSessionAttr(Const.SESSION_USER);
		Iterator<UserDto> list = pageList.iterator();
		// 组装所属角色
		while (list.hasNext()) {
			UserDto u = list.next();
			List<SystemRole> role = roleService.getRole(u.getId());
			u.setRole_names(ListUtil.listToString(role, "name"));
			u.setRole_ids(ListUtil.listToString(role, "id"));
			if (u.getId() == 1 && now.getId() != 1)
				list.remove();
		}

		return new DataGrid<UserDto>(pageList.getPaginator().getTotalCount(),
				pageList.getPaginator().getPage(), pageList);

	}

	@RequestMapping(value = "/select", method = RequestMethod.POST)
	public @ResponseBody DataGrid<UserDto> select(UserDto user,
			DataGrid<UserDto> dataGrid) {
		List<Order> orders = new ArrayList<Order>();
		orders.add(Order.create(dataGrid.getSort(), dataGrid.getOrder()));
		PageList<UserDto> pageList = (PageList<UserDto>) userService
				.getUserList(user, new PageBounds(1, 11, orders, true));
		dataGrid.setPage(pageList.getPaginator().getPage());
		dataGrid.setRows(pageList);
		return dataGrid;
	}

	@RequestMapping(value = "/delete", method = RequestMethod.POST)
	public @ResponseBody Result delete(
			@RequestParam(value = "id", required = true) Integer id) {

		return new Result(userService.deleteByPrimaryKey(id) > 0);

	}

	@RequestMapping(value = "/freeze", method = RequestMethod.POST)
	public @ResponseBody Result freeze(
			@RequestParam(value = "id", required = false) Integer id,
			@RequestParam(value = "status", required = false) Integer status) {
		if (status.equals(1))
			status = 2;
		else
			status = 1;

		return new Result(userService.changeStaus(id, status) > 0);

	}

	@RequestMapping(value = "/batchDelete", method = RequestMethod.GET)
	public @ResponseBody Result batchDelete(
			@RequestParam(value = "ids", required = false) String id) {
		String[] idArray = id.split(",");

		return new Result(userService.batchDelete(idArray));

	}

	@RequestMapping(value = "/batchGrant", method = RequestMethod.POST)
	public @ResponseBody Result batchGrant(
			@RequestParam(value = "ids", required = false) String ids,
			@RequestParam(value = "role_ids", required = false) String[] role_ids) {

		return new Result(userService.batchGrant(
				ListUtil.getParaValuesToInt(role_ids), ids));

	}

	@RequestMapping(value = "/add", method = RequestMethod.POST)
	public @ResponseBody Result add(@ModelAttribute("user") SystemUser user) {
		if (StringUtils.isEmpty(user.getPwd())) {
			user.setPwd(Sec.md5("123456"));
		} else {
			user.setPwd(Sec.md5(user.getPwd()));
		}
		user.setDate(new Date());

		return new Result(userService.insertSelective(user) > 0);

	}

	@RequestMapping(value = "/edit", method = RequestMethod.POST)
	public @ResponseBody Result edit(@ModelAttribute("user") SystemUser user) {

		return new Result(userService.updateByPrimaryKeySelective(user) > 0);

	}

	@RequestMapping(value = "/pwd", method = RequestMethod.POST)
	public @ResponseBody Result pwd(@ModelAttribute("user") SystemUser user) {
		if (StringUtils.isEmpty(user.getPwd())) {
			user.setPwd(Sec.md5("123456"));
		} else {
			user.setPwd(Sec.md5(user.getPwd()));
		}

		return new Result(userService.updateByPrimaryKeySelective(user) > 0);

	}

	@RequestMapping(value = "/grant", method = RequestMethod.POST)
	public @ResponseBody Result grant(
			@RequestParam(value = "role_ids", required = false) String[] role_id,
			@ModelAttribute("user") SystemUser user) {
		Integer[] role_ids = ListUtil.getParaValuesToInt(role_id);

		return new Result(userService.grant(role_ids, user.getId()));

	}
}
